package com.my.socket.bio.v4;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by ZhongGang
 * at 2018/6/28 14:40
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private String host;
    private int port;
    private ServerSocket serverSocket;

    public Server(String host, int port) throws Exception {
        this.host = host;
        this.port = port;

        this.serverSocket = new ServerSocket();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(this.host, this.port);
        this.serverSocket.bind(inetSocketAddress);
    }

    public void startup() throws Exception {
        while (true) {
            Socket socket = this.serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            int b;
            while ((b = inputStream.read()) != -1) {
                LOGGER.info("reading: {}", (char) b);
            }
            LOGGER.info("finish reading");
        }
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        server.startup();
    }
}
